package cn.gok.io;

import java.awt.*;
import java.io.*;

/**
 * @ClassName 对象流
 * @Description TODO
 * @Author HP
 * @Date 9:31 2022/7/8
 * @Version 1.0
 **/
class Weapon implements Serializable{
    private String name;

    public Weapon(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Weapon{" +
                "name='" + name + '\'' +
                '}';
    }
}
class Role implements Serializable {
    private String name;
    private int hp;
    private int level;
    public void beatEnemy(){
        System.out.println(this.name+"在和敌人作战");
    }

    public Role(String name, int hp, int level) {
        this.name = name;
        this.hp = hp;
        this.level = level;
    }

    @Override
    public String toString() {
        return "Role{" +
                "name='" + name + '\'' +
                ", hp=" + hp +
                ", level=" + level +
                '}';
    }

}

class Map implements Serializable{
    private int x;
    private int y;
    private String scene;
    private Weapon weapon;

    public void showScene(){
        System.out.println("地图中出现"+this.scene+"风景");
    }

    public Map(int x, int y, String scene) {
        this.x = x;
        this.y = y;
        this.scene = scene;
    }

    @Override
    public String toString() {
        return "Map{" +
                "x=" + x +
                ", y=" + y +
                ", scene='" + scene + '\'' +
                '}';
    }
}


public class 对象流 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        将对象写入文件();

        从文件中读取();
    }


    private static void 从文件中读取() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day5//1.dat"));
        try {
            while (true) {
                Object obj = ois.readObject();
                if(obj instanceof Role){
                    ((Role) obj).beatEnemy();
                }else if (obj instanceof Map){
                    ((Map) obj).showScene();
                }
                System.out.println(obj);
            }
        }catch (EOFException e){
            System.out.println("文件读取结束");
        }
    }

    private static void 将对象写入文件() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day5//1.dat"));
        Role r1 = new Role("李逍遥",50,10);
        Role r2 = new Role("重楼",30,80);
        Role r3 = new Role("拜月教主",5000,100);
        Map map = new Map(10,20,"仙乐岛");
        oos.writeObject(r1);
        oos.writeObject(r2);
        oos.writeObject(r3);
        oos.writeObject(map);
        oos.close();
        System.out.println("写入成功");
    }


}
